/**
 * 统计数据API
 */
import request from '@/api/request'

/**
 * 总览统计数据
 */
export interface OverviewStats {
  total_leads: number
  new_this_week: number
  conversion_rate: number
  active_leads: number
  closed_won: number
  closed_lost: number
  total_properties: number
  monthly_visits: number
}

/**
 * 来源渠道统计
 */
export interface SourceChartData {
  [key: string]: number
}

/**
 * 阶段漏斗数据
 */
export interface StageFunnelData {
  [key: string]: number
}

/**
 * 客户质量等级分布
 */
export interface QualityDistribution {
  [key: string]: number
}

/**
 * 优先跟进客户
 */
export interface PriorityLead {
  id: number
  name: string
  phone: string
  demand_type: string | null
  quality_score: number | null
  quality_grade: string | null
  stage: string | null
  updated_at: string | null
}

/**
 * 优先跟进列表响应
 */
export interface PriorityFollowupsResponse {
  total: number
  leads: PriorityLead[]
}

/**
 * 统计数据API
 */
export const statsApi = {
  /**
   * 获取总览数据
   */
  async getOverview(): Promise<OverviewStats> {
    const response = await request.get<OverviewStats>('v1/stats/overview')
    return response.data
  },

  /**
   * 获取来源渠道分布
   */
  async getSourceChart(): Promise<SourceChartData> {
    const response = await request.get<SourceChartData>('v1/stats/source-chart')
    return response.data
  },

  /**
   * 获取阶段漏斗数据
   */
  async getStageFunnel(): Promise<StageFunnelData> {
    const response = await request.get<StageFunnelData>('v1/stats/stage-funnel')
    return response.data
  },

  /**
   * 获取客户统计（向后兼容）
   */
  async getLeadsStats(): Promise<{
    by_channel: SourceChartData
    by_stage: StageFunnelData
  }> {
    const response = await request.get<{
      by_channel: SourceChartData
      by_stage: StageFunnelData
    }>('v1/stats/leads')
    return response.data
  },

  /**
   * 获取客户质量等级分布
   */
  async getQualityDistribution(): Promise<QualityDistribution> {
    const response = await request.get<QualityDistribution>('v1/stats/quality-distribution')
    return response.data
  },

  /**
   * 获取今日优先跟进客户列表
   */
  async getPriorityFollowups(limit: number = 10): Promise<PriorityFollowupsResponse> {
    const response = await request.get<PriorityFollowupsResponse>('v1/stats/priority-followups', {
      params: { limit }
    })
    return response.data
  },

  /**
   * 重新计算客户质量评分
   */
  async recalculateQualityScores(limit: number = 100): Promise<{
    updated_count: number
    message: string
  }> {
    const response = await request.post<{
      updated_count: number
      message: string
    }>('v1/stats/recalculate-quality', null, {
      params: { limit }
    })
    return response.data
  }
}
